package com.foreveross.chameleon.mdm;

import android.os.Handler;
import android.os.Looper;
import com.foreveross.chameleon.utils.AppLog;
import com.foreveross.chameleon.utils.PushConstants;
import com.foreveross.chameleon.utils.httputil.HttpConnection;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * author: wzq
 * date: 14-7-31
 * description: 从socket 接收到 mdm信息后的处理的整个流程，中间有线程切换
 */
public class MdmHandlerEntry {
    public final static String TAG = "MdmHandlerEntry";
    private static String URL_GET_MDM = PushConstants.MDM_BASE_URL + "/mdm/api/v1/tasks/{cmdUuid}";
    private static String URL_MDM_RESULT = PushConstants.MDM_BASE_URL + "/mdm/api/v1/tasks/{cmdUuid}";
    private static String MDM_RECIPT_SUCC = "0";//回执成功
    private static String KEY_MDM_RESULT = "cmdResult";// 回执消息体的key

    private String urlPull = null;
    private String urlRecipt = null;
    private ModelMdmCmd mdmCmd = null;

    private String mdmCmdPulled = null; //pull下来的cmd

    public MdmHandlerEntry(JSONObject json) {
        AppLog.i(TAG, "json=\n" + json.toString());

        // 解析获取 id 这个信息
        try {
            String cmdUuid = json.getString("id");
            urlPull = URL_GET_MDM.replace("{cmdUuid}", cmdUuid);
            AppLog.d(TAG, "urlPull=" + urlPull);
            urlRecipt = URL_MDM_RESULT.replace("{cmdUuid}", cmdUuid);
            AppLog.d(TAG, "urlRecipt=" + urlRecipt);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * TODO:处理 mdm信息:拼接url，拉取，执行，发送回执
     */
    public void handleMdm() {
        if (Looper.myLooper() == Looper.getMainLooper()) {//主线程中
            AppLog.i(TAG, "handleMdm in main thread");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    handleMdmPullAndRecipt();
                }
            }).start();
        } else {// 非主线程中
            AppLog.i(TAG, "handleMdm in non-ui thread");
            handleMdmPullAndRecipt();
        }
    }


    // 拉取命令，解析，发送回执【未执行】
    private void handleMdmPullAndRecipt() {
        AppLog.d(TAG, "拉取 url=" + urlPull);
        mdmCmdPulled = HttpConnection.get(urlPull, "application/x-www-form-urlencoded", "application/json");
        AppLog.d(TAG, "pull 下来的mdm指令=\n" + mdmCmdPulled);

        // 解析数据包
        ModelInfoFromServer cmd = ModelInfoFromServer.parseCmd(mdmCmdPulled);
        if (cmd == null || cmd.code != ModelInfoFromServer.RESULT_OK) {
            AppLog.e(TAG, " mdm pull 结果失败 null or code !=0 ");
            return;
        }

        // 解析出命令
        mdmCmd = ModelMdmCmd.getMdmCommand(cmd.cmdContent);
        if (mdmCmd == null || mdmCmd.cmdType == null) {
            AppLog.e(TAG, " content 无法解析成 预设的 mdm 命令");
            return;
        }

        if (mdmCmd.cmdType == MdmCmdType.get_installed_applist) {
            try {
                AppLog.d(TAG, "处理应用程序信息列表的发送");
                LocalInstalledAppInfoUtil.getInstance().setReciptUrl(urlRecipt);
                boolean mdmExecResult = MdmCmdExecutor.getInstance().exec(mdmCmd);
                if (mdmExecResult) {
                    AppLog.i(TAG, "mdm 命令执行成功");
                } else {
                    AppLog.e(TAG, "mdm 执行失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                AppLog.e(TAG, "mdm 执行错误");
            }
        } else if (mdmCmd.cmdType == MdmCmdType.get_device_info) {
            try {
                DeviceInfoMgr.getInstance().setReceptUrl(urlRecipt);
                boolean mdmExecResult = MdmCmdExecutor.getInstance().exec(mdmCmd);
                if (mdmExecResult) {
                    AppLog.i("mdm 命令执行成功");
                } else {
                    AppLog.e("mdm 执行失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                AppLog.e("mdm 执行错误");
            }
        } else if (mdmCmd.cmdType == MdmCmdType.install_app) {
            sendRecipt(MDM_RECIPT_SUCC);
        } else {
            sendRecipt(MDM_RECIPT_SUCC);
        }
    }

    /**
     * 发送回执
     */
    private void sendRecipt(String cmdResult) {
        AppLog.d(TAG, "发送回执");
        final List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
        params.add(new BasicNameValuePair(KEY_MDM_RESULT, cmdResult));
        HttpConnection.put(urlRecipt, params, "application/x-www-form-urlencoded", "application/json");

        // 执行
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                handleMdmExecInUiThread();
            }
        });
    }

    // 解析执行mdm命令
    private void handleMdmExecInUiThread() {
        // 执行命令
        try {
            boolean mdmExecResult = MdmCmdExecutor.getInstance().exec(mdmCmd);
            if (mdmExecResult) {
                AppLog.i(TAG, "mdm 命令执行成功");
            } else {
                AppLog.e(TAG, "mdm 执行失败");
            }
        } catch (Exception e) {
            AppLog.e(TAG, "mdm 执行错误");
            e.printStackTrace();
        }
    }
}
